package cn.mumzone.pos.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.R;
import cn.mumzone.pos.dialog.PosAlertDialog;
import cn.mumzone.pos.model.ReserveOrderEntity;
import cn.mumzone.pos.model.ServiceEntity;
import cn.mumzone.pos.presenter.ReserveDetailPresenter;
import cn.mumzone.pos.presenter.contract.ReserveDetailContract;
import cn.mumzone.pos.ui.adapter.ADA_ReserveDetailService;
import cn.mumzone.pos.ui.widgets.others.FullyLinearLayoutManager;

/**
 * Created by qiuzhenhuan on 2019/6/16.
 */

public class ACT_ReserveDetail extends BaseActivity<ReserveDetailPresenter> implements ReserveDetailContract.View {

    private static final String KEY_RESERVE = "reserve";
    private static final String KEY_RESERVE_ID = "reserve_id";
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_member_title)
    TextView tvMemberTitle;
    @BindView(R.id.tv_member_info)
    TextView tvMemberInfo;
    @BindView(R.id.tv_vip)
    TextView tvVip;
    @BindView(R.id.tv_person_title)
    TextView tvPersonTitle;
    @BindView(R.id.tv_person)
    TextView tvPerson;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_service_title)
    TextView tvServiceTitle;
    @BindView(R.id.rv_services)
    LRecyclerView rvServices;
    @BindView(R.id.ll_services)
    LinearLayout llServices;
    @BindView(R.id.tv_services)
    TextView tvServices;
    @BindView(R.id.ll_goods)
    LinearLayout llGoods;

    @BindView(R.id.btn_cancel_all_hole)
    Button btnCancelAllHole;

    private ReserveOrderEntity mOrderEntity;
    private String mReserveId;

    private ServiceEntity mCancelEntity;

    private ADA_ReserveDetailService serviceAdapter;

    private PosAlertDialog cancelHoldDialog;
    private PosAlertDialog cancelAllHoldDialog;


    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        mOrderEntity = (ReserveOrderEntity) extras.getSerializable(KEY_RESERVE);
        mReserveId = extras.getString(KEY_RESERVE_ID);
    }

    @Override
    protected void initEventAndData() {

        if (mOrderEntity != null) {
            initViewByData();
        } else {
            mPresenter.loadReserveDetail(mReserveId);
        }
    }

    private void initViewByData() {

        initViewByStatus();

        tvVip.setVisibility(StringUtils.isEmpty(mOrderEntity.getBillingUser()) ||
                ReserveOrderEntity.ORDER_STATUS_CLOSED.equals(mOrderEntity.getStatus()) ? View.GONE : View.VISIBLE);
        tvStartTime.setText(AppDateUtil.getDateToString(Long.valueOf(mOrderEntity.getAppointmentTime()), AppDateUtil.YYYY_MM_DD_HH_MM));
        llGoods.setVisibility(View.GONE);


        if(StringUtils.isEmpty(mOrderEntity.getBillName()) && StringUtils.isEmpty(mOrderEntity.getBillPhone())){
            tvMemberInfo.setText("无");
        }else {
            tvMemberInfo.setText(String.format("%s（%s）",
                    StringUtils.get(StringUtils.getUserName(mOrderEntity.getBillName()),"暂无姓名"),mOrderEntity.getBillPhone()));
        }

        if(StringUtils.isEmpty(mOrderEntity.getCouponType()) || "0".equals(mOrderEntity.getCouponType())){
            tvPersonTitle.setVisibility(View.VISIBLE);
            tvPerson.setVisibility(View.VISIBLE);
        }else {
            tvPersonTitle.setVisibility(View.GONE);
            tvPerson.setVisibility(View.GONE);
        }

        tvPerson.setText(StringUtils.get(mOrderEntity.getUserPhone()));

        if(StringUtils.isEmpty(mOrderEntity.getUserName()) && StringUtils.isEmpty(mOrderEntity.getUserPhone())){
            tvPerson.setText("无");
        }else {
            tvPerson.setText(String.format("%s（%s）",
                    StringUtils.get(StringUtils.getUserName(mOrderEntity.getUserName()),"暂无姓名"),mOrderEntity.getUserPhone()));
        }
    }

    private void initViewByStatus() {
        tvStatus.setText(ReserveOrderEntity.ORDER_STATUS_CLOSED.equals(mOrderEntity.getStatus()) ? "（已关闭）" : "（服务中）");
        tvStatus.setTextColor(getResources().getColor(ReserveOrderEntity.ORDER_STATUS_CLOSED.equals(mOrderEntity.getStatus()) ?
                R.color.content_text_color : R.color.order_status_service));
        int textColor;
        if (ReserveOrderEntity.ORDER_STATUS_CLOSED.equals(mOrderEntity.getStatus())) {
            textColor = R.color.content_text_color;
            tvServiceTitle.setVisibility(View.GONE);
            btnCancelAllHole.setVisibility(View.GONE);
        } else {
            textColor = R.color.weak_text_color;
            tvServiceTitle.setVisibility(View.VISIBLE);
            btnCancelAllHole.setVisibility(View.VISIBLE);
        }
        rvServices.setVisibility(View.VISIBLE);
        llServices.setVisibility(View.GONE);

        rvServices.setLayoutManager(new FullyLinearLayoutManager(mContext));
        serviceAdapter = new ADA_ReserveDetailService(mContext);
        serviceAdapter.setClosed(ReserveOrderEntity.ORDER_STATUS_CLOSED.equals(mOrderEntity.getStatus()));
        serviceAdapter.setMember(!StringUtils.isEmpty(mOrderEntity.getBillingUser()));
        serviceAdapter.setOnItemCancelHoldListener(new ADA_ReserveDetailService.OnItemCancelHoldListener() {
            @Override
            public void onItemCancelHold(ServiceEntity serviceEntity) {
                mCancelEntity = serviceEntity;
                cancelHoldDialog = new PosAlertDialog.Builder(mContext)
                        .setRemindText("解除占用后技师可被预约且不可恢复，确认要解除该技师吗？")
                        .setPrimaryText("确认解除")
                        .setPrimaryLoadingText("解除")
                        .setUseLoadingButton(true)
                        .setOnConfirmClickListener(new PosAlertDialog.OnConfirmClickListener() {
                            @Override
                            public void onConfirmClick(View view, Dialog dialog) {
                                mPresenter.doCancelHold(mCancelEntity.getAppointmentId(), mCancelEntity.getId());
                            }
                        }).build();
                cancelHoldDialog.show();
            }
        });
        serviceAdapter.setData(mOrderEntity.getServices());
        rvServices.setAdapter(new LRecyclerViewAdapter(serviceAdapter));
        rvServices.setHasFixedSize(true);
        rvServices.setPullRefreshEnabled(false);
        rvServices.setLoadMoreEnabled(false);

        tvMemberInfo.setTextColor(getResources().getColor(textColor));
        tvPerson.setTextColor(getResources().getColor(textColor));
        tvStartTime.setTextColor(getResources().getColor(textColor));
        tvServices.setTextColor(getResources().getColor(textColor));


    }

    @Override
    protected int getLayout() {
        return R.layout.act_reserve_detail;
    }

    @OnClick({R.id.iv_back, R.id.btn_back, R.id.btn_cancel_all_hole})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_cancel_all_hole:
                cancelAllHoldDialog = new PosAlertDialog.Builder(mContext)
                        .setRemindText("完成订单后释放全部技师且不可恢复，确认要完成订单吗？")
                        .setPrimaryText("确认完成")
                        .setPrimaryLoadingText("完成中")
                        .setUseLoadingButton(true)
                        .setOnConfirmClickListener(new PosAlertDialog.OnConfirmClickListener() {
                            @Override
                            public void onConfirmClick(View view, Dialog dialog) {
                                mPresenter.doCancelAllHold(mOrderEntity.getId());
                            }
                        }).build();
                cancelAllHoldDialog.show();
                break;
        }
    }

    public static void startAc(Context context, ReserveOrderEntity entity) {
        Intent intent = new Intent(context, ACT_ReserveDetail.class);
        intent.putExtra(KEY_RESERVE, entity);
        context.startActivity(intent);
    }

    public static void startAc(Context context, String reserveId) {
        Intent intent = new Intent(context, ACT_ReserveDetail.class);
        intent.putExtra(KEY_RESERVE_ID, reserveId);
        context.startActivity(intent);
    }

    @Override
    public void showCancelHoldSuccess() {
        if (cancelHoldDialog != null) {
            cancelHoldDialog.cancelLoading();
        }
        PosToast.INSTANCE.makeCheckMarkToast(mContext, "已解除");
        boolean isAllServiceCancel = true;
        if (!ListUtil.isListEmpty(mOrderEntity.getServices())) {
            for (ServiceEntity entity : mOrderEntity.getServices()) {
                if (entity.getId().equals(mCancelEntity.getId())) {
                    entity.setSuborderStatus("3");
                }
                if (!entity.getSuborderStatus().equals("3")) {
                    isAllServiceCancel = false;
                }
            }
        }
        if (isAllServiceCancel) {
            mOrderEntity.setStatus("3");
            initViewByStatus();
            return;
        }

        if (serviceAdapter != null) {
            serviceAdapter.setData(mOrderEntity.getServices());
            serviceAdapter.notifyDataSetChanged();
        }


    }

    @Override
    public void showCancelAllHoldSuccess() {
        if (cancelAllHoldDialog != null) {
            cancelAllHoldDialog.cancelLoading();
        }
        PosToast.INSTANCE.makeCheckMarkToast(mContext, "已完成");
        mOrderEntity.setStatus("3");
        initViewByStatus();
    }

    @Override
    public void showError(String msg) {
        if (cancelAllHoldDialog != null) {
            cancelAllHoldDialog.cancelLoading();
        }
        if (cancelHoldDialog != null) {
            cancelHoldDialog.cancelLoading();
        }
        super.showError(msg);
    }

    @Override
    public void showReserveDetail(ReserveOrderEntity orderEntity) {
        this.mOrderEntity = orderEntity;
        initEventAndData();
    }
}
